package com.gulimall.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description
 * @Author lhj
 * @Date 2024/3/11 19:29
 */
@Controller
@RequestMapping("/sso/server")
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 根据token获取登录的用户
     * @param token token
     * @return string
     */
    @ResponseBody
    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam(value = "token") String token) {
       return redisTemplate.opsForValue().get(token);
    }

    /**
     * 如果没有登录跳转到登录页，如果登录重定向到访问路径并带上token
     * @param redirectUrl 重定向地址
     * @param ssoToken 登录下发token
     * @param model 域对象
     * @return string
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam(value = "redirect_url") String redirectUrl, @CookieValue(value = "sso_token",required = false) String ssoToken, Model model) {
        if (!StringUtils.isEmpty(ssoToken)) {
            return "redirect:" + redirectUrl + "?token=" + ssoToken;
        }
        model.addAttribute("redirectUrl", redirectUrl);
        return "login";
    }

    /**
     * 处理用户登录
     * @param username 用户名
     * @param password 密码
     * @param redirectUrl 回到地址
     * @return string
     */
    @PostMapping("/doLogin")
    public String doLogin(String username, String password, @RequestParam(value = "redirect_url") String redirectUrl, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set(token, username);
            Cookie cookie = new Cookie("sso_token", token);
            response.addCookie(cookie);
            return "redirect:" + redirectUrl + "?token=" + token;
        }
        return "login";
    }
}
